<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-export>
            <el-button :disabled="!canExport" @click="inventoryExport()"
              >出库</el-button
            >
          </template>
          <template v-slot:filter-revoke>
            <el-button :disabled="!canRevoke" @click="revoke()">撤回</el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </table-container>
    </div>

    <inventory-and-export-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :order-id="modifyInfo.orderId"
      @returnModify="returnModify"
    />

    <inventory-and-export-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row="detailInfo.data"
      @returnBack="getList"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
  </div>
</template>

<script setup name="inventoryAndExport">
import TableContainer from '@/components/TableContainer/index'
import {
  inventoryExportOrdersPage,
  inventoryExportOrdersDelete,
  inventoryExportOrdersSubmit,
  inventoryExportOrdersExecute,
  inventoryExportOrdersRevoke,
} from '@/api/stock.js'
import InventoryAndExportModify from './modify'
import InventoryAndExportDetail from './detail'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/index')
)
const AdvancedSearch = defineAsyncComponent(() =>
  import('@/components/AdvancedSearch/index')
)
const detailList = defineAsyncComponent(() => import('./detailList'))

// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    customizeUserVO: {},
    queryMap: {
      depotAuth: {
        asTbName: 'inventory_export_order',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    /* {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('inventoryAndExport:add'),
    }, */
    {
      type: 'slot',
      value: 'export',
      show: proxy.$permission('inventoryAndExport:export'),
    },
    {
      type: 'slot',
      value: 'revoke',
      show: proxy.$permission('inventoryAndExport:revoke'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('inventoryAndExport:submit'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '撤回',
        event: revoke,
        show: proxy.$permission('inventoryAndExport:revoke'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '出库',
        event: inventoryExport,
        show: proxy.$permission('inventoryAndExport:export'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('inventoryAndExport:update'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('inventoryAndExport:delete'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
    ],
  },
})
const modifyInfo = reactive({
  visible: false,
  orderId: '',
  title: '',
})
const detailListInfo = reactive({
  visible: false,
})
const detailInfo = reactive({
  visible: false,
  data: {},
})
const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const time = ref([])

watch(
  () => proxy.$route,
  (route) => {
    if (route.name === 'inventoryAndExport') {
      const params = route.params
      if (params && params.id) {
        detailInfo.data.id = params.id
        detailInfo.visible = true
        modifyInfo.visible = false
      }
    }
  },
  { immediate: true }
)
const canExport = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => item.status !== 2).length
  )
})
const canRevoke = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => item.status !== 2).length
  )
})

let obj = {
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'inventory_export_order_status',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'inventoryAndExport' && el.url === val.url) {
                detailInfo.visible = false
                modifyInfo.visible = false
                detailInfo.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailInfo.visible = true
                    detailInfo.data = {
                      id: val.orderId || val.businessId,
                      orderNo: val.orderNo || '',
                    }
                    sessionStorage.setItem('storeRowId', val.orderId || val.businessId)
                    console.log(detailInfo, 11111111)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

function returnModify() {
  if (modifyInfo.orderId) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'inventory_export_order',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  ]
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
//删除
function remove(row) {
  const data = []
  data.push(row.id)
  inventoryExportOrdersDelete(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//创建
function create() {
  modifyInfo.orderId = ''
  modifyInfo.title = '新增出库单'
  modifyInfo.visible = true
}
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.orderId = row.id
  modifyInfo.title = '修改出库单'
  modifyInfo.visible = true
}
//提交
function submit(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  }
  inventoryExportOrdersSubmit(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function inventoryExport(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  inventoryExportOrdersExecute(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function revoke(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  inventoryExportOrdersRevoke(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.data = row
  detailInfo.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'inventoryExportOrderPage-com.slip.spd.entity.vo.stock.InventoryExportOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = inventoryExportOrdersPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
